from selenium.webdriver.chrome.options import Options
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException

from spiders.config import driver_path


class WebDriverWrapper:
    def __init__(self, headless=False):
        """初始化ChromeDriver"""
        # 设置Chrome浏览器选项
        chrome_options = Options()
        if headless:
            # chrome_options.add_argument("--headless")  # 无头模式，不显示浏览器
            chrome_options.add_argument('--disable-gpu')
            chrome_options.add_argument('--window-size=1920,1080')

        # 如果driver_path 为空，则使用默认路径
        # 设置ChromeDriver服务
        service = Service(driver_path)

        # 启动浏览器
        self.driver = webdriver.Chrome(service=service, options=chrome_options)
        self.driver.implicitly_wait(10)  # 设置隐式等待，避免元素加载不及时

    def open_url(self, url):
        """打开指定的URL"""
        self.driver.get(url)

    def find_element(self, by, value):
        """查找页面元素"""
        return self.driver.find_element(by, value)

    def click_element(self, by, value):
        """点击页面元素"""
        element = self.find_element(by, value)
        element.click()

    def input_text(self, by, value, text):
        """输入文本到元素"""
        element = self.find_element(by, value)
        element.clear()
        element.send_keys(text)

    def close(self):
        """关闭浏览器"""
        self.driver.quit()

    def scroll_to_element(self, by, value):
        """滚动页面到指定元素"""
        element = self.find_element(by, value)
        self.driver.execute_script("arguments[0].scrollIntoView();", element)

    def wait_for_seconds(self, seconds):
        """等待指定时间"""
        time.sleep(seconds)

    def open_page(self, url):
        """打开网页"""
        self.driver.get(url)
        self.driver.maximize_window()

    def get_chapter_links(self):
        """获取当前页所有章节的链接"""
        chapter_urls = []
        try:
            # 定位所有章节链接 (根据实际页面结构调整选择器)
            chapters = driver.find_elements(By.CSS_SELECTOR, 'a.chapter-link-selector')
            for chapter in chapters:
                chapter_urls.append(chapter.get_attribute('href'))
        except Exception as e:
            print(f"Error while fetching chapters: {e}")
        return chapter_urls

    def click_next_page(self):
        try:
            # 等待并点击“下一页”按钮
            next_button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, 'a.next-page-selector'))  # 调整为实际页面的选择器
            )
            next_button.click()
            time.sleep(2)  # 等待页面加载完成
        except Exception as e:
            print(f"Error while clicking next page: {e}")
            raise e  # 如果没有下一页，抛出异常以停止循环

    def crawl_all_chapters(self, start_url):
        """爬取所有章节"""
        all_chapter_links = []
        self.open_page(start_url)

        while True:
            # 获取当前页的章节链接
            chapter_links = self.get_chapter_links()
            all_chapter_links.extend(chapter_links)
            print(f"抓取到 {len(chapter_links)} 个章节链接")

            # 点击下一页，如果下一页不存在则终止循环
            if not self.click_next_page():
                break

            time.sleep(2)  # 等待页面加载

        self.driver.quit()
        return all_chapter_links


# 示例使用
if __name__ == "__main__":
    driver_path = r"C:\soft\javaStudy\PythonCode\novel-spider\chromedriver\chromedriver.exe"  # 你的 ChromeDriver 路径
    novel_url = "https://zbwq.wmg.weimeigu.net/app/index.php?i=16414&c=entry&tid=25699&do=mulu&m=iweite_xiaoshuo"

    spider = WebDriverWrapper(headless=False)
    all_chapters = spider.crawl_all_chapters(novel_url)

    print("所有章节链接：")
    for link in all_chapters:
        print(link)
